package com.yryp.sign.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yryp.sign.entry.SignPerson;
import com.yryp.sign.mq.utils.MqrsaUtil;
import com.yryp.sign.web.service.SignService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by kongyunhui on 2017/4/7.
 */
@Component
public class Receiver implements ChannelAwareMessageListener {

    Pattern chinesePattern = Pattern.compile(".*[\u4e00-\u9fa5]+.*");

    private final Logger logger = LoggerFactory.getLogger(Receiver.class);

    @Autowired
    private SignService signService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String body = new String(message.getBody());
        try {
            // 解密数据
            body = MqrsaUtil.decryptRSA(body);
        } catch (Exception e) {
            logger.error("RSA decode error, please check your src data");
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            return;
        }
        //同步信息
        SignPerson signPerson = JSON.parseObject(body, SignPerson.class);
        String srcName = signPerson.getName();
        if (StringUtils.isNotEmpty(srcName)) {
            Matcher m = chinesePattern.matcher(srcName);
            if (StringUtils.isNotEmpty(srcName)) {
                if (m.find()) {
                    //去掉所有空字符
                    String newName = srcName.replaceAll("[ |　]+", "").replaceAll("\\s", "");
                    signPerson.setName(newName);
                }
            }
        }
        signService.syncData(signPerson);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}